<?php

namespace app\services\wechat;

use app\home\model\Config;
use app\services\wechat\Wxbizdatacrypt;
use app\model\config\ConfigModel;
use think\Exception;
use think\facade\Cache;
use think\facade\Log;
use think\facade\Request;

class Miniprogram
{

    //如果显式地声明构造函数，那么它的访问权限必须是 public，而且构造函数是在实例化时自动调用的，我们不需要手动调用。
    //静态方法的特点
    //1.静态方法只能操作静态变量
    //2.静态方法不能操作非静态变量.
    //构造方法只在实例化时调用，静态方法没有实例生成，不会调用构造方法
    public function __construct(){
        $config = [
            // 必要配置
            'appid' => Config::getConfigValue('appid'),
            'appSecret' => Config::getConfigValue('appSecret'),
            'mch_id'             => Config::getConfigValue('mch_id'),
            'key'                => Config::getConfigValue('apikey'),   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
        ];
        $this->config=$config;
    }




    public  function getAccessToken(){
        $url_get = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->config["appid"] . "&secret=" . $this->config["appSecret"];
        $data = curlGet($url_get);
        $output = json_decode($data, true);
        if (!isset($output['access_token'])){
            throw new Exception('接口调用凭据失败');
        }
        return $output['access_token'];
    }

    // 获取用户信息
    public function get_user_info($code)
    {
        $url_get = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $this->config["appid"] . "&secret=" . $this->config["appSecret"] . "&js_code=" . $code . "&grant_type=authorization_code";
        $data = curlGet($url_get);
        $output = json_decode($data, true);
        return $output;
    }





    /**
     * code  encryptedData iv
     */
    public function getPhoneNumber($encryptedData,$iv,$session_key,$return){
        $WXBizDataCrypt =new Wxbizdatacrypt($this->config["appid"],$session_key);
        $errCode    = $WXBizDataCrypt->decryptData($encryptedData,$iv,$return);
        $return=json_decode($return, true);
        Log::write('获取手机号'.json_encode($return),'info');
        return $return['phoneNumber'];
    }



    //发送匹配订阅消息
    public function sendMessage($messageinfo,$tm_id,$openid)
    {
        //赛事报名通知
        $template_id="";
        if($tm_id=="signup"){
            $template_id = 'sA5dqrJ_dBCyZuWIBVFCtuhgrIpJnKwUbtXZGtriVWQ';
            $page='pages/index/index';
        }elseif($tm_id=="matching"){ //报名的匹配成功  对战开始提醒
            $template_id = 'mhmNRh7nrRamdWbUY94sBBsx3j0Eu_5A52BVuEU';
            $page='pages/index/index';
        }
        $appid = $this->config["appid"];
        $appsecret = $this->config["appSecret"];
        $touser = $openid; //接收者（用户）的 openid

        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        $res = json_decode(file_get_contents($url),true);
        $access_token = $res['access_token'] ;
        //请求url
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token ;
        //发送内容
        $data = [] ;
        //接收者（用户）的 openid
        $data['touser'] = $touser;
        //所需下发的订阅模板id
        $data['template_id'] = $template_id ;
        //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
        $data['page'] = $page;
        //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
        $data['data']=$messageinfo;
        //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        $data['miniprogram_state'] = 'formal' ;
        return curlPost($url,json_encode($data)) ;
    }



    public function generateUrlLink($mobile,$usercode){
        $accessToken=$this->getAccessToken();

        $url_POST="https://api.weixin.qq.com/wxa/generate_urllink?access_token=".$accessToken;

        $postdata['path'] = '/pages/punchTheClock/index/index';  //参数

        $postdata['query']='type=junling&mobile='.$mobile.'&usercode='.$usercode;

        //$postdata['env_version']='trial';

        //小程序的详情页路径
        $res = curlPost($url_POST,json_encode($postdata,true)); //post请求

        $output=json_decode($res,true);

        return $output['url_link'];
    }

}